﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
 
namespace DAL
{
    public class AccessDBHelp
    {

        //读取配置文件连接字符串
        //"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=BookSystemDB.accdb;Jet OLEDB:Database Password=123456"
        //"Provider=Microsoft.ACE.OLEDB.4.0;Data Source=BookSystemDB.mdb;Jet OLEDB:Database Password=123456"
        //public static readonly string connstr1 = System.Configuration.ConfigurationManager.AppSettings["connstr"].ToString();
        public static readonly string connstr = Properties.sql.Default.accessStr;
        
            
        //public static readonly string connstr1 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=BookSystemDB.accdb;Jet OLEDB:Database Password=123456";
        public static int ExecuteNonQuery(string cmdText,  params OleDbParameter[] parameters)
       {
              using (OleDbConnection conn =new OleDbConnection(connstr))
            {
                 conn.Open();
                 using (OleDbCommand cmd = conn.CreateCommand())
                    {
                       cmd.CommandText = cmdText;
                       cmd.CommandTimeout = 3000;
                        if (parameters != null)
                        {
                            cmd.Parameters.AddRange(parameters);
                        }
                       return cmd.ExecuteNonQuery();
                    }
             }
        }

        private static OleDbConnection connection;
        /// <summary>
        /// 获取连接数据库对象
        /// </summary>
        public static OleDbConnection GetConnection
        {
            get
            {
                string strConn = connstr;
                if (connection == null)
                {
                    connection = new OleDbConnection(strConn);
                    connection.Open();
                }
                else if (connection.State == ConnectionState.Closed)
                {
                    connection = new OleDbConnection(strConn);
                    connection.Open();
                }
                else if (connection.State == ConnectionState.Broken)
                {
                    connection.Close();
                    connection.Open();
                }
                return connection;
            }
        }


        public static object ExecuteScalar(string cmdText,params OleDbParameter[] parameters)
            {
                  using (OleDbConnection conn = new OleDbConnection(connstr))
                    {
                       conn.Open();
                      using (OleDbCommand cmd = conn.CreateCommand())
                           {
                               cmd.CommandText = cmdText;
                               cmd.CommandTimeout = 3000;
                               cmd.Parameters.AddRange(parameters);
                               return cmd.ExecuteScalar();
                            }
                    }
              }
 
          public static DataTable ExecuteDataTable(string cmdText,params OleDbParameter[] parameters)
           {
                   using (OleDbConnection conn = new OleDbConnection(connstr))
                     {
                         conn.Open();
                         using (OleDbCommand cmd = conn.CreateCommand())
                           {
                              cmd.CommandText = cmdText;
                              cmd.CommandTimeout = 3000;
                             cmd.Parameters.AddRange(parameters);
                                using (OleDbDataAdapter adapter = new OleDbDataAdapter(cmd))
                                     {
                                        DataTable dt = new DataTable();
                                        adapter.Fill(dt);
                                        return dt;
                                      }
                               }
                         }
                    }
           public static DataSet ExecuteDataSet(string cmdText,params OleDbParameter[] parameters)
            {
            if (parameters ==null)
            {
                DataSet ds = new DataSet();
                OleDbDataAdapter adapter = new OleDbDataAdapter(cmdText, GetConnection);
                //adapter.SelectCommand.Parameters.AddRange(param);
                adapter.Fill(ds);
                return ds;
            }
          

            using (OleDbConnection conn = new OleDbConnection(connstr))
                    {
                         conn.Open();
                         using (OleDbCommand cmd = conn.CreateCommand())
                          {
                              cmd.CommandText = cmdText;
                              cmd.CommandTimeout = 3000;
                              cmd.Parameters.AddRange(parameters);
                             using (OleDbDataAdapter adapter = new OleDbDataAdapter(cmd))
                                  {
                                       DataSet dt =new DataSet();
                                        adapter.Fill(dt);
                                        return dt;
                                   }
                             }
                        }
                  }
         
        public static OleDbDataReader ExecuteDataReader(string cmdText,params OleDbParameter[] parameters)
            {
                 OleDbConnection conn = new OleDbConnection(connstr);
                 conn.Open();
                using (OleDbCommand cmd = conn.CreateCommand())
                  {
                        cmd.CommandText = cmdText;
                        cmd.CommandTimeout = 3000;
                        
                if (parameters != null)
                {

                    cmd.Parameters.AddRange(parameters);
                }
                        return cmd.ExecuteReader(CommandBehavior.CloseConnection);
                  }
               }

        /// <summary>
        /// ACCESS高效分页
        /// </summary>
        /// <param name="pageIndex">当前页码</param>
        /// <param name="pageSize">分页容量</param>
        /// <param name="strKey">主键</param>
        /// <param name="showString">显示的字段</param>
        /// <param name="queryString">查询字符串，支持联合查询</param>
        /// <param name="whereString">查询条件，若有条件限制则必须以where 开头</param>
        /// <param name="orderString">排序规则</param>
        /// <param name="pageCount">传出参数：总页数统计</param>
        /// <param name="recordCount">传出参数：总记录统计</param>
        /// <returns>装载记录的DataTable</returns>
        public static DataTable ExecutePager(int pageIndex, int pageSize, string strKey, string showString, string queryString, string whereString, string orderString, out int pageCount, out int recordCount)
        {
            if (pageIndex < 1) pageIndex = 1;
            if (pageSize < 1) pageSize = 10;
            if (string.IsNullOrEmpty(showString)) showString = "*";
            if (string.IsNullOrEmpty(orderString)) orderString = strKey + " asc ";
            OleDbConnection m_Conn = GetConnection;

            try
            {
                m_Conn.Open();
            }
            catch { }
            string myVw = string.Format(" ( {0} ) tempVw ", queryString);
            OleDbCommand cmdCount = new OleDbCommand(string.Format(" select count(*) as recordCount from {0} {1}", myVw, whereString), m_Conn);

            recordCount = Convert.ToInt32(cmdCount.ExecuteScalar());

            if ((recordCount % pageSize) > 0)
                pageCount = recordCount / pageSize + 1;
            else
                pageCount = recordCount / pageSize;
            OleDbCommand cmdRecord;
            if (pageIndex == 1)//第一页
            {
                cmdRecord = new OleDbCommand(string.Format("select top {0} {1} from {2} {3} order by {4} ", pageSize, showString, myVw, whereString, orderString), m_Conn);
            }
            else if (pageIndex > pageCount)//超出总页数
            {
                cmdRecord = new OleDbCommand(string.Format("select top {0} {1} from {2} {3} order by {4} ", pageSize, showString, myVw, "where 1=2", orderString), m_Conn);
            }
            else
            {
                int pageLowerBound = pageSize * pageIndex;
                int pageUpperBound = pageLowerBound - pageSize;
                string recordIDs = recordID(string.Format("select top {0} {1} from {2} {3} order by {4} ", pageLowerBound, strKey, myVw, whereString, orderString), pageUpperBound);
                string queryStringend = string.Format("select {0} from {1} where {2} in ({3}) order by {4} ", showString, myVw, strKey, recordIDs, orderString);
                cmdRecord = new OleDbCommand(queryStringend, m_Conn);

            }
            OleDbDataAdapter dataAdapter = new OleDbDataAdapter(cmdRecord);
            DataTable dt = new DataTable();
            dataAdapter.Fill(dt);
            m_Conn.Close();
            m_Conn.Dispose();
            return dt;

        }

        /// <summary>
        /// 分页使用
        /// </summary>
        /// <param name="query"></param>
        /// <param name="passCount"></param>
        /// <returns></returns>
        private static string recordID(string query, int passCount)
        {
            OleDbConnection m_Conn = GetConnection;

            try
            {
                m_Conn.Open();
            }
            catch { }
            OleDbCommand cmd = new OleDbCommand(query, m_Conn);
            string result = string.Empty;
            using (OleDbDataReader dr = cmd.ExecuteReader())
            {
                while (dr.Read())
                {
                    if (passCount < 1)
                    {
                        result += "," + dr.GetInt32(0);
                    }
                    passCount--;
                }
            }
            // m_Conn.Close();
            // m_Conn.Dispose();
            return result.Substring(1);

        }
    }


        }
